﻿using Heroius.Extension;
using Heroius.Extension.WPF;
using Heroius.Files;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Heroius.LocSync
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Setting = new SyncSetting();
            {
                var latestsetting = Properties.Settings.Default.LatestSetting;
                if (!string.IsNullOrWhiteSpace(latestsetting) && File.Exists(latestsetting))
                {
                    OpenSetting(latestsetting);
                }
            }
            HomeResetResponse();

            diaopen = new OpenFileDialog()
            {
                Filter = "LocSync配置|*.ls",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            };
            diasave = new SaveFileDialog()
            {
                Filter = "LocSync配置|*.ls",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            };
        }

        /// <summary>
        /// 活动配置
        /// </summary>
        public SyncSetting Setting { get; set; }

        #region 双击响应

        private void Left2Click(object sender, MouseButtonEventArgs e)
        {
            DoubleClickResponse(FViewLeft, FViewRight, e);
        }

        private void Right2Click(object sender, MouseButtonEventArgs e)
        {
            DoubleClickResponse(FViewRight, FViewLeft, e);
        }

        void DoubleClickResponse(FolderView active, FolderView positive, MouseButtonEventArgs e)
        {
            var name = active.SelectedItem.Name;
            switch (active.SelectedItem.Type)
            {
                default:
                case Extension.WPF.FolderItemInfoType.File:
                    {
                        if (MessageBox.Show("是否将当前文件复制（覆盖）到另一侧？", "注意", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            File.Copy(active.SelectedItem.Path, $"{positive.CurrentFolderPath}/{name}", true);
                            positive.RefreshViewItems(); //由于控件暂不支持监视文件变动，因此需要手动刷新
                        }
                    }
                    break;
                case Extension.WPF.FolderItemInfoType.Folder:
                    {
                        if (positive.CurrentItems.Contains(item => item.Name == name))
                        {
                            positive.CurrentFolderPath = positive.CurrentItems.First(item => item.Name == name).Path;
                        }
                        else
                        {
                            if (MessageBox.Show("另一侧不存在对应文件夹，是否创建？", "注意", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                            {
                                var ndir = $"{positive.CurrentFolderPath}\\{name}";
                                Directory.CreateDirectory(ndir);
                                positive.CurrentFolderPath = ndir;
                                e.Handled = false;
                            }
                            else
                            {
                                e.Handled = true;
                            }
                        }
                    }
                    break;
            }
        }

        #endregion

        #region 上下文菜单复制

        private void LeftCopyItem(object sender, RoutedEventArgs e)
        {
            CopyItemResponse(FViewLeft, FViewRight);
        }

        private void RightCopyItem(object sender, RoutedEventArgs e)
        {
            CopyItemResponse(FViewRight, FViewLeft);
        }

        void CopyItemResponse(FolderView active, FolderView positive)
        {
            var name = active.ContextMenuItem.Name;
            switch (active.ContextMenuItem.Type)
            {
                case FolderItemInfoType.File:
                    File.Copy(active.ContextMenuItem.Path, $"{positive.CurrentFolderPath}/{name}", true);
                    break;
                case FolderItemInfoType.Folder:
                    FolderCopy.DirectoryCopy(active.ContextMenuItem.Path, $"{positive.CurrentFolderPath}/{name}", true);
                    break;
            }
            positive.RefreshViewItems(); //由于控件暂不支持监视文件变动，因此需要手动刷新
        }

        private void LeftSmartItem(object sender, RoutedEventArgs e)
        {
            SmartCopyResponse(FViewLeft, FViewRight);
        }

        private void RightSmartItem(object sender, RoutedEventArgs e)
        {
            SmartCopyResponse(FViewRight, FViewLeft);
        }

        void SmartCopyResponse(FolderView active, FolderView positive)
        {
            MessageBox.Show("smart copy 将比较源与目标的文件时间与hash，并结合当前目录下的 .locsync 文件夹下同名文件配置进行判断 是否要执行覆盖操作。");
        }

        #endregion

        #region 工具栏操作

        private void HomeReset_Click(object sender, RoutedEventArgs e)
        {
            HomeResetResponse();
        }

        /// <summary>
        /// 将两个FolderView重置为设置目录
        /// </summary>
        void HomeResetResponse()
        {
            FViewLeft.CurrentFolderPath = Setting.Left;
            FViewRight.CurrentFolderPath = Setting.Right;
        }

        private void ParentFolder_Click(object sender, RoutedEventArgs e)
        {
            ParentFolderResponse();
        }

        void ParentFolderResponse()
        {
            var lp = Directory.GetParent(FViewLeft.CurrentFolderPath);
            var rp = Directory.GetParent(FViewRight.CurrentFolderPath);
            if (lp == null || rp == null)
            {
                MessageBox.Show("至少一侧达到目录的上限");
                return;
            }
            else
            {
                FViewLeft.CurrentFolderPath = lp.FullName;
                FViewRight.CurrentFolderPath = rp.FullName;
            }
        }

        /// <summary>
        /// copy selected items to the other side, from the active side of course
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        void MultiCopy(FolderView from, FolderView to)
        {
            if (from.SelectedItems.Count()>0)
            {
                foreach (var item in from.SelectedItems)
                {
                    switch (item.Type)
                    {
                        case FolderItemInfoType.File:
                            File.Copy(item.Path, $"{to.CurrentFolderPath}/{item.Name}", true);
                            break;
                        case FolderItemInfoType.Folder:
                            FolderCopy.DirectoryCopy(item.Path, $"{to.CurrentFolderPath}/{item.Name}", true);
                            break;
                    }
                }
                to.RefreshViewItems();
            }
        }

        private void MultiCopyLeft_Click(object sender, RoutedEventArgs e)
        {
            MultiCopy(FViewLeft, FViewRight);
        }

        private void MultiCopyRight_Click(object sender, RoutedEventArgs e)
        {
            MultiCopy(FViewRight, FViewLeft);
        }
        #endregion

        #region 主菜单响应

        private void EditSetting_Click(object sender, RoutedEventArgs e)
        {
            new SyncWindow(Setting).ShowDialog();
            HomeResetResponse();
        }

        OpenFileDialog diaopen;
        SaveFileDialog diasave;

        private void OpenSetting_Click(object sender, RoutedEventArgs e)
        {
            if (diaopen.ShowDialog() == true)
            {
                OpenSetting(diaopen.FileName);
                Properties.Settings.Default.LatestSetting = diaopen.FileName;
                Properties.Settings.Default.Save();
            }
        }
        /// <summary>
        /// load setting from spec file, with ui validation
        /// </summary>
        /// <param name="filepath"></param>
        void OpenSetting(string filepath)
        {
            EntitySilo silo = new EntitySilo();
            silo.Load(filepath);
            silo.Fetch("sides", Setting);

            if (!Directory.Exists(Setting.Left))
            {
                MessageBox.Show("所加载配置的左侧目录不存在，将自动设置成默认值！");
                Setting.Left = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            }
            if (!Directory.Exists(Setting.Right))
            {
                MessageBox.Show("所加载配置的右侧目录不存在，将自动设置成默认值！");
                Setting.Right = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);
            }

            HomeResetResponse();
        }

        private void SaveSetting_Click(object sender, RoutedEventArgs e)
        {
            if (diasave.ShowDialog() == true)
            {
                EntitySilo silo = new EntitySilo();
                silo.Store("sides", Setting);
                silo.Save(diasave.FileName);

                Properties.Settings.Default.LatestSetting = diasave.FileName;
                Properties.Settings.Default.Save();
            }
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show($"LocSync v{Assembly.GetExecutingAssembly().GetName().Version.ToString()}\r\n" +
                $"Heroius @ EnvSafe Co.,Ltd. {DateTime.Now.ToString("yyyy")}", "关于");
        }

        #endregion

 
    }
}
